package com.stx.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.stx.entity.Film;
import com.stx.service.FilmService;

public class AddFilm extends ActionSupport {

	private Film film;
	private FilmService fs;
	
	private File file; // 上传文件的文件内容那个
	private String fileFileName; // 上传文件的文件名
	private String fileContentType; // 上传文件的MIME类型
	
	public File getFile() {
		return file; 
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public Film getFilm() {
		return film;
	}

	public void setFilm(Film film) {
		this.film = film;
	}

	public FilmService getFs() {
		return fs;
	}

	public void setFs(FilmService fs) {
		this.fs = fs;
	}

	/*
	 * 添加电影
	 * 先把图片写了
	 * 修改默认添加时间
	 * 然后是对图片的处理
	 * */
	public String addFilm() {
		System.out.println(film.getFi_releasetime());
		//得到图片的保存路径
		 String path=ServletActionContext.getServletContext().getRealPath("/images/film");
		 String imagePath;
		 String imageName;
		 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		 imageName=sdf.format(new Date())+".jpg";
	     imagePath=path+"//"+imageName;
	     File getFile=new File(imagePath);
	     FileInputStream fis;
		 try {
				fis = new FileInputStream(file);
				FileOutputStream fos = new FileOutputStream(getFile);
				int t = 0;
				while ((t = fis.read()) > -1) {
					fos.write(t);
				}
				fis.close();
				fos.flush();
				fos.close();
				
				/*
				 * 添加电影的其它默认信息
				 * 录入时间
				 * 评论人数
				 * 图片地址
				 * */
			    film.setFi_time(new Date());
			    film.setFi_comments(0);
			    film.setFi_image("images/film/"+imageName);
			    fs.addFilm(film);
			    addActionError("保存成功");
				return "success";
			} catch (FileNotFoundException e) {
				addActionError("图像修改失败");
				e.printStackTrace();
			} catch (IOException e) {
				addActionError("图像修改失败");
				e.printStackTrace();
			}catch(Exception e){
				addActionError("失败");
				getFile.delete();
				e.printStackTrace();
			}
			return "success";
	}
	
	
}
